var UtilHttp = {}

UtilHttp.kReqType = {
    post: "POST",
    get: "GET"
}

UtilHttp.API_TIMEOUT = 5 * 1000           //请求api接口的超时时间 在js上面是毫秒

UtilHttp.__reqPost = function (url, tbdata, sucfunc, failfunc) {
    var xhr = cc.loader.getXMLHttpRequest()

    xhr.timeout = this.API_TIMEOUT

    xhr.open(kReqType["post"], url)
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 207)) {
            sucfunc(xhr.response)
        }
        else { failfunc(xhr.response) }

    }
    if (typeof tbdata != "string") {
        tbdata = json.encode(tbdata)
    }
    else {
        tbdata = tostring(tbdata)
    }
    xhr.send(tbdata)
}

UtilHttp.__reqGet = function (url, sucfunc, failfunc) {
    var xhr = cc.loader.getXMLHttpRequest()
    xhr.timeout = this.API_TIMEOUT
    xhr.open(this.kReqType["get"], url)
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 207)) {
            sucfunc(xhr.response)
        }
        else { failfunc(xhr.response) }

    }
    xhr.send()
}

//get下载文件的统一封装
UtilHttp.__reqDownload = function (url, filename, timeout, callback, failcallback) {
    var xhr = cc.loader.getXMLHttpRequest()
    xhr.timeout = this.API_TIMEOUT
    xhr.open(this.kReqType["get"], url)
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 207)) {
            sucfunc(xhr.response)
        }
        else { failfunc(xhr.response) }

    }
    xhr.send()
}

/**
 * 发起get请求
 * 
 * @param {string} url 
 * @param {function} sucfunc 
 * @param {function} failfunc 
 */
UtilHttp.getUrl = function(url, sucfunc, failfunc){
    this.__reqGet(url, sucfunc, failfunc)
}

/**
 * encodeURL
 * 
 * @param {string} s 
 * @returns 
 */
UtilHttp.encodeURL = function(s){
    return encodeURI(s)
}

/**
 * decodeURL
 * 
 * @param {string} s 
 * @returns 
 */
UtilHttp.decodeURL = function(s){
    return decodeURI(s)
}

/**
 * 发起post请求
 * 
 * @param {string} url 
 * @param {Object} tbdata 
 * @param {function} sucfunc 
 * @param {function} failfunc 
 */
UtilHttp.postUrl = function(url, tbdata, sucfunc, failfunc){
    this.__reqPost(url, tbdata, sucfunc, failfunc)
}


UtilHttp.downFile = function(url, savefilename, timeout, callback, failcallback){
    // todo
}
